/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.bus.web;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.Util;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.ResponseResult;
import com.thinkgem.jeesite.common.utils.EnumProperty;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.bus.entity.Vaccine;
import com.thinkgem.jeesite.modules.bus.service.VaccineService;
import com.thinkgem.jeesite.modules.sys.entity.Attachment;
import com.thinkgem.jeesite.modules.sys.service.AttachmentService;

import org.springframework.web.bind.annotation.RequestBody;


/**
 * 疫苗补助Controller
 * @author zhangxingliang
 * @version 2019-06-10
 */
@Controller
@RequestMapping(value = "${adminPath}/bus/vaccine")
public class VaccineController extends BaseController {

	@Autowired
	private VaccineService vaccineService;
	@Autowired
	private AttachmentService attachmentService;
	@ModelAttribute
	public Vaccine get(@RequestParam(required=false) String id) {
		Vaccine entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = vaccineService.get(id);
		}
		if (entity == null){
			entity = new Vaccine();
		}
		return entity;
	}
	
	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = {"list", ""})
	public String list(Vaccine vaccine, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Vaccine> page = vaccineService.findPage(new Page<Vaccine>(request, response), vaccine); 
		model.addAttribute("page", page);
		return "modules/bus/vaccineList";
	}

	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "form")
	public String form(Vaccine vaccine, Model model) {
		model.addAttribute("vaccine", vaccine);
		return "modules/bus/vaccineForm";
	}

	@RequiresPermissions("bus:vaccine:edit")
	@RequestMapping(value = "save")
	public String save(Vaccine vaccine, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, vaccine)){
			return form(vaccine, model);
		}
		vaccineService.save(vaccine);
		addMessage(redirectAttributes, "保存疫苗补助成功");
		return "redirect:"+Global.getAdminPath()+"/bus/vaccine/?repage";
	}
	
	@RequiresPermissions("bus:vaccine:edit")
	@RequestMapping(value = "delete")
	public String delete(Vaccine vaccine, RedirectAttributes redirectAttributes) {
		vaccineService.delete(vaccine);
		addMessage(redirectAttributes, "删除疫苗补助成功");
		return "redirect:"+Global.getAdminPath()+"/bus/vaccine/?repage";
	}

	/**
	 *
	 * @Title: provinceRejectIndex
	 * @author: sy
	 * @date: 2019年06月26日 17:33
	 * @Description: 省级驳回记录左侧树
	 * @param vaccine
	 * @param request
	 * @param response
	 * @param model
	 * @return: java.lang.String
	 */
	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "provinceRejectIndex")
	public String provinceRejectIndex(Vaccine vaccine, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/bus/provinceRejectIndex";
	}

	/**
	 *
	 * @Title: provinceRejectList
	 * @author: sy
	 * @date: 2019年06月11日 8:39
	 * @Description: 省级驳回记录列表
	 * @param vaccine
	 * @param request
	 * @param response
	 * @param model
	 * @return: java.lang.String
	 */
	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "provinceRejectList")
	public String provinceRejectList(Vaccine vaccine, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Vaccine> page = vaccineService.provinceRejectList(new Page<Vaccine>(request, response), vaccine);
		model.addAttribute("page", page);
		model.addAttribute("vaccine", vaccine);
		return "modules/bus/provinceRejectList";
	}

	/**
	 *
	 * @Title: provinceRejectList
	 * @author: sy
	 * @date: 2019年06月11日 16:17
	 * @Description: 省级补助记录左侧树
	 * @param vaccine
	 * @param request
	 * @param response
	 * @param model
	 * @return: java.lang.String
	 */
	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "provinceVaccineIndex")
	public String provinceVaccineIndex(Vaccine vaccine, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/bus/provinceVaccineIndex";
	}

	/**
	 *
	 * @Title: provinceVaccineList
	 * @author: sy
	 * @date: 2019年06月11日 16:23
	 * @Description: 省级补助记录列表
	 * @param vaccine
	 * @param request
	 * @param response
	 * @param model
	 * @return: java.lang.String
	 */
	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "provinceVaccineList")
	public String provinceVaccineList(Vaccine vaccine, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Vaccine> page = vaccineService.provinceVaccineList(new Page<Vaccine>(request, response), vaccine);
		model.addAttribute("vaccine",vaccine);
		model.addAttribute("page", page);
		return "modules/bus/provinceVaccineList";
	}

	/**
	 *
	 * @Title: provinceReject
	 * @author: sy
	 * @date: 2019年06月11日 19:28
	 * @Description: 省级一键驳回
	 * @param vaccine
	 * @param request
	 * @param response
	 * @param model
	 * @return: java.lang.String
	 */
	@ResponseBody
	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "provinceReject")
	public ResponseResult provinceReject(Vaccine vaccine, HttpServletRequest request, HttpServletResponse response, Model model) {
		vaccineService.provinceReject(vaccine);
		return ResponseResult.success();
	}

	/**
	 *
	 * @Title: provinceRejectForm
	 * @author: sy
	 * @date: 2019年06月12日 16:35
	 * @Description: 省级驳回表单
	 * @param vaccine
	 * @param request
	 * @param response
	 * @param model
	 * @return: java.lang.String
	 */
	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "provinceRejectForm")
	public String provinceRejectForm(Vaccine vaccine, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/bus/provinceRejectForm";
	}

	/**
	 * 
	 * @Title: view
	 * @author: sy
	 * @date: 2019年06月13日 8:50
	 * @Description: 疫苗补助查看
	 * @param vaccine
	 * @param request
	 * @param response
	 * @param model
	 * @return: java.lang.String
	 */
	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "vaccineView")
	public String view(Vaccine vaccine, HttpServletRequest request, HttpServletResponse response, Model model) {
		Vaccine va=vaccineService.vaccineView(vaccine);
		List<Attachment> attachmentList=attachmentService.attachmentList(va.getId(),"bus_vaccine");
		va.setAttachmentList(attachmentList);
		model.addAttribute("vaccine",va);
		return "modules/bus/vaccineView";
	}

	/**
	 *
	 * @Title: vaccineUncheckedList
	 * @author: mengying
	 * @date: 2019年06月13日 16:28
	 * @Description: 补助待审核审核页
	 * @param vaccine
	 * @param request
	 * @param response
	 * @param model
	 * @return: com.thinkgem.jeesite.modules.bus.entity.Vaccine
	 */
	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "vaccineUncheckedList")
	public String vaccineUncheckedList(Vaccine vaccine, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Vaccine> page = vaccineService.vaccineUncheckedList(new Page<Vaccine>(request, response),vaccine,EnumProperty.AuditTypeEnum.UNREVIEWED.getKey());
		model.addAttribute("page", page);
		return "modules/bus/vaccineUncheckedList";
	}
	/**
	 *
	 * @Title: vaccineCheckedList
	 * @author: mengying
	 * @date: 2019年06月13日 19:02
	 * @Description: 补助已审核审核页
	 * @param vaccine
	 * @param request
	 * @param response
	 * @param model
	 * @return: com.thinkgem.jeesite.modules.bus.entity.Vaccine
	 */
	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "vaccineCheckedList")
	public String vaccineCheckedList(Vaccine vaccine, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Vaccine> page = vaccineService.vaccineUncheckedList(new Page<Vaccine>(request, response),vaccine, EnumProperty.AuditTypeEnum.REVIEWED.getKey());
		model.addAttribute("page", page);
		return "modules/bus/vaccineCheckedList";
	}
	/**
	 *
	 * @Title: vaccineRecord
	 * @author: mengying
	 * @date: 2019年06月13日 19:02
	 * @Description: 补助记录
	 * @param vaccine
	 * @param request
	 * @param response
	 * @param model
	 * @return: com.thinkgem.jeesite.modules.bus.entity.Vaccine
	 */
	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "vaccineRecord")
	public String vaccineRecord(Vaccine vaccine, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Vaccine> page = vaccineService.vaccineUncheckedList(new Page<Vaccine>(request, response),vaccine, EnumProperty.AuditTypeEnum.SUCCESS.getKey());
		model.addAttribute("page", page);
		return "modules/bus/vaccineRecord";
	}
	/**
	 *
	 * @Title: updateVaccineStatus
	 * @author: mengying
	 * @date: 2019年06月14日 17:02
	 * @Description: 补助改变审核状态
	 * @param auditOpinion
	 * @param auditId
	 * @return: com.thinkgem.jeesite.modules.bus.entity.Vaccine
	 */
    @RequiresPermissions("bus:vaccine:view")
    @RequestMapping(value = "updateVaccineStatus")
    //@ResponseBody
    public String updateVaccineStatus(String auditId,String updateFlag,String auditOpinion,String id,RedirectAttributes redirectAttributes) {
        if(vaccineService.updateVaccineStatus(auditId, updateFlag, auditOpinion, id)){
        	if(EnumProperty.AuditTypeEnum.SUCCESS.getKey().equals(updateFlag)){
				addMessage(redirectAttributes, "审核成功");
			}else{
				addMessage(redirectAttributes, "申请已驳回");
			}
        }else{
            addMessage(redirectAttributes, "审核失败!");
        }
		return "redirect:" + Global.getAdminPath() + "/bus/vaccine/vaccineUncheckedList/?repage";
//    if(vaccineService.updateVaccineStatus(auditId, updateFlag, auditOpinion, id)){
//       return EnumProperty.AuditTypeEnum.SUCCESS.getKey();
//    }else{
//       return EnumProperty.AuditTypeEnum.UNREVIEWED.getKey();
//    }
    }

    /**
    *@Title:checkInvoice
    *@Author: zyj
    *@Date: 2019/8/11 15:51
    *@Description: 发票验真
    *@Param: [vaccine, request, response]
    *@Return: com.thinkgem.jeesite.common.persistence.ResponseResult
    */
	@ResponseBody
	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "checkInvoice")
	public ResponseResult checkInvoice(Vaccine vaccine, HttpServletRequest request, HttpServletResponse response, Model model) {
		vaccineService.checkInvoiceUpdate(vaccine);
		return ResponseResult.success();
	}

	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "vaccineViewCheck")
	public String vaccineViewCheck(Vaccine vaccine, HttpServletRequest request, HttpServletResponse response, Model model) {
		Vaccine va = vaccineService.findVaccine(vaccine);
		va.setVaccineImg(vaccine.getVaccineImg());
		model.addAttribute("vaccine",va);
		return "modules/bus/vaccineViewCheck";
	}
	/**
	 *
	 * @Title: imageView
	 * @author: my
	 * @date: 2019年08月19日
	 * @Description: 图片预览
	 * @return: java.lang.String
	 */
	@RequestMapping(value = "imageView")
	public String imageView(String imagePath, Model model) {
		model.addAttribute("imagePath",imagePath);
		return "modules/bus/imageView";
	}

	/**
	 * @author Zhang Xingliang
	 * @description PC端发票验真处理
	 * @date 14:19 2019/6/28
	 * @params []
	 * @return com.thinkgem.jeesite.common.persistence.ResponseResult
	 **/
	@ResponseBody
	@RequiresPermissions("bus:vaccine:view")
	@RequestMapping(value = "checkInvoiceReal", method = RequestMethod.POST)
	public ResponseResult check(Vaccine vaccine) {
		if(vaccine.getTotalAmount() == null){
			vaccine.setTotalAmount(new BigDecimal("0.00"));
		}
		Map<String,Object> map = checkInvoiceReal(vaccine);
		JSONObject realResult = (JSONObject)JSONObject.parse(map.get("response").toString());
		JSONObject message = (JSONObject)realResult.get("message");
		if ("2".equals(message.get("status").toString()) ) {//查询成功
			JSONArray invoice = realResult.getJSONArray("invoice");
			JSONObject veritem = (JSONObject)invoice.get(0);
			JSONArray veritemArr = (JSONArray)veritem.get("veritem");
			JSONObject content = (JSONObject)veritemArr.get(20);
			if ("1".equals(content.get("content").toString())) {// 1未作废 2已作废
				map.put("msg","success");
				vaccine.setState("1");
			} else {
				vaccine.setState("2");
				map.put("msg","invalid");//发票已经作废，无法作为补助凭证！
			}
		} else if ("20".equals(message.get("status").toString())) {//您上传的发票今日已超出查验次数，请明日在试！
			vaccine.setState("2");
			map.put("msg","20");
		} else {
			// 查询发票不规范或无效发票，请重新上传正确的发票！;
			vaccine.setState("0");
			map.put("msg","fail");
		}
		vaccineService.checkInvoiceUpdate(vaccine);
		return ResponseResult.success(map);
	}

	public Map<String,Object> checkInvoiceReal(Vaccine vaccine){
		Map<String,Object> map = new HashMap<>();
		OkHttpClient client = new OkHttpClient();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		okhttp3.RequestBody body = new MultipartBody.Builder()
				.setType(MultipartBody.FORM)
				.addFormDataPart("key", Global.getConfig("invoiceKey"))
				.addFormDataPart("secret", Global.getConfig("invoiceSecret"))
				.addFormDataPart("typeId", "3007")//需修改为对应产品ID
				.addFormDataPart("format", "json")
				.addFormDataPart("invoiceCode", vaccine.getInvoiceCode())
				.addFormDataPart("invoiceNumber", vaccine.getInvoiceNo())
				.addFormDataPart("billingDate", df.format(vaccine.getInvoiceDate()))
				.addFormDataPart("totalAmount", vaccine.getTotalAmount().toString())
				.addFormDataPart("checkCode", vaccine.getCheckCode())
				.build();
		Request request = new Request.Builder()
				.url("https://netocr.com/verapi/verInvoice.do")
				.post(body)
				.build();
		try {
			Response response = client.newCall(request).execute();
			String returnMsg = response.body().string();
			if (response.isSuccessful()){
				map.put("response",returnMsg);
			}else {
				map.put("response","{\"message\":{\"status\":\"fail\"}}");
			}
		} catch (IOException e) {
			map.put("response","{\"message\":{\"status\":\"fail\"}}");
			e.printStackTrace();
		}
		return map;
	}
}